package com.example.cachetext.service;

import com.example.cachetext.entity.Comment;
import com.example.cachetext.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class ApiCommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private RedisTemplate redisTemplate;

    public Comment findCommentById(Integer id){
        //comment_api 是缓存空间的名称
        Object object = redisTemplate.opsForValue().get("comment_api" + id);
        if (object != null){
            return (Comment) object;
        }
        else {
            Optional<Comment> comment = commentRepository.findById(id);
            if (comment.isPresent()){
                redisTemplate.opsForValue().set("comment_api" + id,comment.get());
            }
            return comment.get();
        }
    }

    public void updateComment(Integer id,String content) {
        commentRepository.updateComment(id,content);
        redisTemplate.opsForValue().set("comment_api" + id,findCommentById(id));
    }

    public void deleteCommentById(Integer id) {
        commentRepository.deleteById(id);
        redisTemplate.delete("comment_api" + id);
    }
}
